neutron.setTitle("File Upload")
neutron.setMinSize(220, 160)
neutron.setWinSize(220, 160)
neutron.getInfo((data) => {
    if (data[0]["x"] <= -100) {
        neutron.setPosition(20, 20)
    }
});

var file_list = []
var file_obj_list = []
let setchunkSize = 1024 * 1024 * 4;
let currentFileIndex = 0;
var offset = 0;

function min(a, b) {
    if (a > b) {
        return b
    }
    return a
}

function readChunk(file, chunkSize, sizes) { // 读文件块
    return new Promise((resolve, reject) => {
        let reader = new FileReader();
        let chunk = file.slice(offset, min(offset + chunkSize, sizes));

        reader.onload = function (e) {
            if (reader.result) {
                offset += chunkSize;
                resolve(reader.result)
            }
        };

        reader.onerror = function (err) {
            console.error('Error reading file:', err);
            reject(err);
        };

        reader.readAsArrayBuffer(chunk);
    });
}


function upload() {
    neutron.setPosition(-150, -150) // 隐藏窗口
    neutron.setWinSize(1, 1)
    if (window.parent.window.NEUTRON_TASKS_OPENED != true) { // 如果没有打开任务面板
        neutron.createIframeWin("Tasks", "/api/plugin/tasks/iframe/index.html")
    }
    document.getElementsByTagName('body')[0].innerHTML = ''
    var ws = new WebSocket(API_PATH + "/upload");
    ws.onopen = function () {
        ws.send(JSON.stringify({ // 发送文件信息
            "files": file_list,
            "dist": window.location.hash.substring(1)
        }));
    }
    ws.onmessage = function (event) { // 下一文件块
        if (currentFileIndex >= file_obj_list.length) {
            return
        }
        if (offset >= file_obj_list[currentFileIndex].size) {
            offset = 0;
            currentFileIndex++
            if (currentFileIndex >= file_obj_list.length) {
                neutron.close()
                return
            }
        }
        readChunk(file_obj_list[currentFileIndex], setchunkSize, file_obj_list[currentFileIndex].size)
            .then((res) => { // 发送
                ws.send(res)
            })
            .catch(error => {
                console.error('Error reading chunk:', error);
                neutron.close()
            });
    };
}

function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
}

window.onload = function () { // 初始化
    var main_obj = document.getElementById('main_btn');
    // 拖拽
    (['dragenter', 'dragover', 'dragleave', 'drop']).forEach(eventName => {
        main_obj.addEventListener(eventName, preventDefaults, false);
    });
    main_obj.addEventListener('drop', function (e) { // 拖拽上传
        const files = e.dataTransfer.files;
        if (files.length == 0) {
            return
        }
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            file_list.push({
                "name": file.name,
                "size": file.size,
                "path": file.webkitRelativePath.substring(0, file.webkitRelativePath.lastIndexOf('/'))
            })
            file_obj_list.push(file)
        }
        upload()
    })
    document.getElementById('upload_dist_text').innerText = decodeURIComponent(window.location.hash.substring(2) + "/")
    document.getElementById('main_btn').addEventListener('click', function () {
        document.getElementById('fileInput').click() // 打开文件选择框
    })
    document.getElementById('upload_dir_text').addEventListener('click', function (e) {
        document.getElementById('dirInput').click() // 打开文件夹选择框
        e.preventDefault()
        e.stopPropagation()
    })
    document.getElementById('dirInput').addEventListener('change', function (event) { // 选择文件夹
        const files = event.target.files;
        if (files.length == 0) {
            return
        }
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            file_list.push({
                "name": file.name,
                "size": file.size,
                "path": file.webkitRelativePath.substring(0, file.webkitRelativePath.lastIndexOf('/'))
            })
            file_obj_list.push(file)
        }
        upload()
    });
    document.getElementById('fileInput').addEventListener('change', function (event) { // 选择文件
        const files = event.target.files;
        if (files.length == 0) {
            return
        }
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            file_list.push({
                "name": file.name,
                "size": file.size,
                "path": ""
            })
            file_obj_list.push(file)
        }
        upload()
    });

}